package net.lab1024.sa.admin.module.basedata.customer.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.lab1024.sa.admin.module.basedata.customer.domain.dto.CustomerDTO;
import net.lab1024.sa.admin.module.basedata.customer.domain.entity.Customer;
import net.lab1024.sa.admin.module.basedata.customer.domain.entity.CustomerLicense;
import net.lab1024.sa.admin.module.basedata.customer.mapper.CustomerBankMapper;
import net.lab1024.sa.admin.module.basedata.customer.mapper.CustomerContactMapper;
import net.lab1024.sa.admin.module.basedata.customer.mapper.CustomerLicenseMapper;
import net.lab1024.sa.admin.module.basedata.customer.mapper.CustomerMapper;
import net.lab1024.sa.base.common.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CustomerLicenseService {

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private CustomerBankMapper customerBankMapper;
    @Autowired
    private CustomerLicenseMapper customerLicenseMapper;
    @Autowired
    private CustomerContactMapper customerContactMapper;

    public Customer saveOrUpdateCustomer(CustomerDTO customerDTO) {
        return null;
    }


    /**
     * 根据客户编码查询客户营业执照表
     *
     * @param customerCode
     * @return
     */
    public CustomerLicense getCustomerLicenseByCustomerCode(String customerCode) {
        if (customerCode == null) {
            throw new BusinessException("查询客户营业执照信息,客户编号不能为空");
        }
        LambdaQueryWrapper<CustomerLicense> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerLicense::getCustomerCode, customerCode);
        return customerLicenseMapper.selectOne(wrapper);
    }

    public void saveOrUpdateCustomerLicense(CustomerLicense customerLicense) {
        if (customerLicense == null) {
            throw new BusinessException("保存客户营业执照信息,参数不能为空");
        }
        if (customerLicense.getCustomerCode() == null) {
            throw new BusinessException("保存客户营业执照信息,客户编号不能为空");
        }

        CustomerLicense customerLicenseOld = getCustomerLicenseByCustomerCode(customerLicense.getCustomerCode());
        if (customerLicenseOld != null) {
            customerLicenseMapper.deleteById(customerLicenseOld);
        }
        customerLicense.setVersion(customerLicense.getVersion() + 1);
        customerLicenseMapper.insert(customerLicense);
    }
}
